import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  // 获取 token
  const token = localStorage.getItem('zbox-token')

  // 如果已经在登录页面，直接放行
  if (to.path === '/login' && token) {
    router.push('/')
    return
  } else if (to.path === '/login' && !token) {
    next()
    return
  } else if (to.path !== '/login' && !token) {
    router.push('/login')
    return
  }
  // 其他情况正常放行
  next()
})

export default router
